package com.xsd.awen.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xsd.awen.config.WebResult;
import com.xsd.awen.domain.entity.App;
import com.xsd.awen.domain.entity.Task;
import com.xsd.awen.domain.po.AppPagePo;
import com.xsd.awen.domain.vo.AppVo;
import com.xsd.awen.mapper.AppMapper;
import com.xsd.awen.mapper.TaskMapper;
import com.xsd.awen.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

@Service
@Scope(proxyMode= ScopedProxyMode.TARGET_CLASS)
public class AppService {

    @Autowired
    AppMapper appMapper;

    @Autowired
    TaskMapper taskMapper;

    public PageInfo<AppPagePo> page(AppVo appVo){
        PageHelper.startPage(appVo.getPage(),appVo.getLimit());
        return new PageInfo<>(appMapper.page(appVo));
    }

    public String save(App app){
        Integer count = appMapper.countApp(app);
        if( count != null && count > 0 ){
            return WebResult.ERROR("用户名重复");
        }
        app.setId(UUIDUtils.generate());
        appMapper.insert(app);
        return WebResult.OK();
    }

    public String update(App app){
        Integer count = appMapper.countUpdateApp(app);
        if( count != null && count > 0 ){
            return WebResult.ERROR("用户名重复");
        }
        appMapper.updateById(app);
        return WebResult.OK();
    }

    public String delete(App app){

        Task task = new Task();
        task.setAppId(app.getId());
        Integer count = taskMapper.countTaskByAppId(task);
        if( count != null && count > 0 ){
            return WebResult.ERROR("应用下有任务，不能删除");
        }else{
            appMapper.deleteById(app);
            return WebResult.OK();
        }


    }

    public App getById(String id){
        App app = appMapper.selectById(id);
        return app;
    }

}
